package util

import (
	"time"
)

//"2006-01-02 15:04:05"
func GetFormatDateNow(formatString string) string {
	return time.Now().Format(formatString)
}

// DatetimeToMilliSecond 日期时间格式转换成毫秒
func DatetimeToMilliSecond(datetime string) int64 {
	datetime = UTCTransLocal(datetime, "2006-01-02 15:04:05.999999")
	loc, _ := time.LoadLocation("Local") //获取时区
	tmp, _ := time.ParseInLocation("2006-01-02 15:04:05.999999", datetime, loc)
	return tmp.UnixNano() / 1e6
}

//时间戳转年月日
func DateFormatYmd(timestamp int) string {
	tm := time.Unix(int64(timestamp), 0)
	return tm.Format("2006-01-02")
}

//时间戳转年月日
func DateFormat(timestamp int, formatString string) string {
	tm := time.Unix(int64(timestamp), 0)
	return tm.Format(formatString)
}

//时间戳
func DateUnix() int {
	t := time.Now().Local().Unix()
	return int(t)
}

//获取n天前时间并格式化
func DateBeforeFormat(day int) string {
	//获取两天前的时间
	currentTime := time.Now()
	oldTime := currentTime.AddDate(0, 0, day) //若要获取3天前的时间，则应将-2改为-3
	//oldTime 的结果为go的时间time类型，2018-09-25 13:24:58.287714118 +0000 UTC
	return oldTime.Format("2006-01-02")
}

//根据定义时间往前推
func DateSelfBeforeFormat(day int, date string) string {
	loc, _ := time.LoadLocation("Asia/Shanghai")           //设置时区
	tt, _ := time.ParseInLocation("2006-01-02", date, loc) //2006-01-02 15:04:05是转换的格式如php的"Y-m-d H:i:s"
	oldTime := tt.AddDate(0, 0, day)                       //若要获取3天前的时间，则应将-2改为-3
	//oldTime 的结果为go的时间time类型，2018-09-25 13:24:58.287714118 +0000 UTC
	return oldTime.Format("2006-01-02")
}

func UTCTransLocal(utcTime string, format string) string {
	loc, _ := time.LoadLocation("Asia/Shanghai") //设置时区
	t, _ := time.ParseInLocation(time.RFC3339, utcTime, loc)
	if format == "" {
		return t.Local().Format("2006-01-02 15:04:05")
	} else {
		return t.Local().Format(format)

	}
}

func TransLocal(utcTime string, format string) string {
	loc, _ := time.LoadLocation("Asia/Shanghai") //设置时区
	t, _ := time.ParseInLocation("2006-01-02 15:04:05", utcTime, loc)
	return t.Local().Format(format)
}
